package com.unit.test;


import com.unit.test.model.User;
import com.unit.test.service.ServiceA;
import com.unit.test.service.ServiceB;
import com.unit.test.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.util.ReflectionTestUtils;

import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;

@Slf4j
public class MockitoTest_Mock extends BaseTest {

    //需要mock注入的服务
    // InjectMocks 加 Autowired 可以对bean对象中的部分属性。
    @InjectMocks
    @Autowired
    private ServiceA serviceA;

    //需要mock注入的服务
    @InjectMocks
    @Autowired
    private ServiceB serviceB;

    //需要mock掉的服务
    @Mock
    private UserService userService;

    //初始化mock注入
    @Before
    public void initMock() {
        MockitoAnnotations.initMocks(this);
        ReflectionTestUtils.setField(serviceB,"userService",userService);
    }

    @Test
    public void test() {
        User user = new User();
        Integer mockAge = 88;
        user.setName("张三");
        user.setAge(mockAge);

        //mock掉ServiceC的getUser()方法，返回指定的user对象
        when(userService.getById(anyInt())).thenReturn(user);


        //调用需要测试的方法，结果将是mock结果
        User resultUser = serviceA.getUserVo(123);
        log.info(resultUser.toString());
        Assert.assertEquals(mockAge, resultUser.getAge());
    }
}



